<?php
namespace app\api\service;
use think\Request;
use app\api\model\Unit;
use app\api\model\Product;

class UnitService {
    public function page($page = 1, $size = 10){
        $data 	= Request::instance()->get();
        $where 	= [];

        empty($data['position']) || $where['position'] = $data['position'];
        empty($data['name']) || $where['name'] = ['like','%'.$data['name']];

        $obj = Unit::where($where)
        ->paginate($size, false, ['page' => $page]);

        if ($obj->isEmpty()){
            return [];
        }
        return $obj->toArray();
    }

    public function all(){
        return show(1, 'ok', Unit::all(), 200);
    }

    public function save(){ 
        $param = Request::instance()->param();	//获取参数

        if (!isset($param['id']) || !is_numeric($param['id']))
        {
            // 新增
            $obj = new Unit;

            try {
                $obj->name = $param['name'];
            }catch(Exption $e) {
                return show(0, '修改失败', [], 200);
            }
            if( $obj->save()){
                return show(1, '新增成功', [], 200);
            }
        }else {
            // 更新
            $obj = Unit::get($param['id']);
            try {
                $obj->name = $param['name'];
            }catch(Exption $e) {
                return show(0, '修改失败', [], 200);
            }
            // 检测错误
            if( $obj->save()){
                return show(1, '修改成功', [], 200);
            }
        }
        
        return show(0, '修改失败', [], 200);
    }

    public function delete($id){

        $p = Product::where('unit_id', $id)->find();

        if ($p) {
            return show(0, '当前单位有商品在使用，无法删除~');
        }

    	if( Unit::destroy($id, true) ){
            return show(1, '删除成功', [], 200);
        }
        
        return show(0, '删除失败', [], 200);
    }
}